package it.univpm.diiga.semanticsearch.ricerca;
import it.univpm.diiga.semanticsearch.servizi.Link;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;



public class RicercaWeb extends Ricerca{

	public RicercaWeb() throws Exception {
		super();
		
		// TODO Auto-generated constructor stub
	}


	private final String URL_MOTORE_RICERCA="http://ajax.googleapis.com/ajax/services/search/web";
	private final String HTTP_REFERER = "http://www.example.com/";
	private final String WEB_REPO="Web Search";
	private int totalPage=0;
	
	public List<Link> execSearch(String keyword) throws Exception{
		   
		   List<Link> lista=new ArrayList<Link>();
		  //try {
		    int start=0;
			JSONArray ja=null;
		    boolean stopSearch=false;
		    boolean addItem=true;
		    do{
				String query=keyword+" filetype:wsdl OR filetype:bpel OR filetype:swasl AND -filetype:html";
				query = URLEncoder.encode(query, "UTF-8");
				URL url = new URL(URL_MOTORE_RICERCA+"?start="+start+"&rsz=large&v=1.0&q=" + query);
				URLConnection connection = url.openConnection();
				connection.addRequestProperty("Referer", HTTP_REFERER);
				connection.setConnectTimeout(10000);
				// Get the JSON response
				String line;
				StringBuilder builder = new StringBuilder();
				BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
				while((line = reader.readLine()) != null) {
				    builder.append(line);
				   }	
				
				String response = builder.toString();
				JSONObject json = new JSONObject(response);
				
				 try{
					ja = json.getJSONObject("responseData").getJSONArray("results");
				  }catch(JSONException e){
						//e.printStackTrace();
						stopSearch=true;
						addItem=false;
				  } 
				  if (addItem){
					for (int i = 0; i< ja.length(); i++) {
					    JSONObject j = ja.getJSONObject(i);
					    
					    String servName=j.getString("titleNoFormatting").toString();
					    String link=j.getString("url").toLowerCase();
					    String ext = link.substring(link.lastIndexOf('.')+1, link.length());
					    
					    Link serv=null;
					    if (ext.equals("wsdl"))
					    	serv=new Link(servName,link,link,null,null,WEB_REPO);
					    if (ext.equals("bpel"))
					    	serv=new Link(servName,link,null,link,null,WEB_REPO);
					    if (ext.equals("swasl"))
					    	serv=new Link(servName,link,null,null,link,WEB_REPO);
		
		                
		                lista.add(serv);
					    
					}
					try{
						 
						JSONArray totalResultArray=json.getJSONObject("responseData").getJSONObject("cursor").getJSONArray("pages");
						totalPage=totalResultArray.length();
						stopSearch=((totalPage)*8==start);
						start=start+8;
						if (totalPage==1)
							stopSearch=true;
					}catch(JSONException e){
						stopSearch=true;
						addItem=false;
					}
				  }
				

		    }while(!stopSearch);
		   //}
		   /*catch(JSONException e){
		    	System.out.println("ciao");
		    	e.printStackTrace();
				//throw new Exception();
		    }*/
		/*} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		return lista;
	}
	
	
}
